window.pageProductAll = [];
function omesaasProduct(option) {
    if (!option.product || option.product instanceof Array) {
        return false;
    }
    window.pageProductAll.push(this);

    this.product = option.product;

    this.optionLength = option.product.options.length;

    this.params = {
        quantity: option.quantity || 1,
        price: option.product.variant_price_min,
        src: option.product.src,
        is_main_product: option.isMainProduct || false,
        block_id: option.block_id || "",
        productTitle: option.product.title,
        product_id: option.product.id
    };

    this.attrOption = []; //sku选项

    this.oldAttrOption = []; //老sku选项

    this.cartShake = true; //添加购物车提交限制

    this.buyShake = true; //立即购买提交限制

    this.changeOption = option.changeOption; // 选择sku触发事件

    this.isMainProduct = option.isMainProduct || false; // 是否主商品

    this.block_id = option.block_id || new Date().getTime(); // 当前积木块id

    this.data_from = option.data_from || ""; //页面来源

    this.ec_currency_code = option.ec_currency_code || ""; //当前货币符号

    // this.handleRender = option.handleRender;
    this.variant = option.product.variants; // sku变体

    this.renderOption = option.renderOption || true; // 是否渲染规格

    // if (option.product.variant instanceof Array) {
    //     this.variant = option.product.variant;
    // } else {
    //     this.variant = option.product.variants;
    // }

    // 是否渲染规格
    if (this.renderOption) {
        this.formDom = $(option.id);

        this.numberNode = this.formDom.find(".product-price-number");

        this.marketNode = this.formDom.find(".product-price-market");

        this.skuNode = this.formDom.find(".sku-cell");
        
        // 初始化库存显示元素
        this.inventoryNode = $(this.formDom).find(".product-detail-inventory");

        const tempID = `#omesaas-product-sku-${themeConfig.global.product_option_type || "default"}`;
        this.skuTemplate = $(tempID).html();

        const self = this;
        this.skuNode.on("click", ".product-sku-values-item", function (params) {
            const item = $(this).data("value");
            const index = $(this).data("index");
            //是否库存空能否购买
            if (!self.isCurrentOptionBuy(item)) {
                return false;
            }
            self.attrOption[index - 1].selected_value = item.value;
            self.attrOption[index - 1].selected_value_label = item.name;

            for (let i = 0; i < self.optionLength; i++) {
                self.attrOption[i].value = [];
            }
            self.setSkuOption();
        });

        this.skuNode.on("change", ".product-sku-unselect", function (params) {
            const item = $(this).find("option:selected").data("value");
            const index = $(this).find("option:selected").data("index");
            //是否库存空能否购买
            if (!self.isCurrentOptionBuy(item)) {
                return false;
            }
            self.attrOption[index - 1].selected_value = item.value;
            for (let i = 0; i < self.optionLength; i++) {
                self.attrOption[i].value = [];
            }
            self.setSkuOption();
        });
    }
    this.initSku();
}

omesaasProduct.prototype.initSku = function () {
    const self = this;
    const copyList = JSON.parse(JSON.stringify(this.variant));

    // var minPriceItem = copyList.sort((a, b) => a.price - b.price);
    //查询第一个满足库存不为0的数据
    let FirstPriceItemIndex = 0;
    if (this.product.inventory_policy !== 2 && this.product.inventory_tracking === 1) {
        FirstPriceItemIndex = copyList.findIndex((el) => el.inventory_quantity > 0);
    }
    // const FirstPriceItemIndex = copyList.findIndex((el) => el.inventory_quantity > 0);

    const checkedSkuInfo = this.checkedSKu();

    if (this.optionLength) {
        //多规款
        const selected = FirstPriceItemIndex === -1 ? false : this.isCurrentOptionBuy(copyList[FirstPriceItemIndex]);

        for (let i = 0; i < this.optionLength; i++) {
            var selected_value = "";
            var selected_value_label = "";

            //默认选中
            if (selected) {
                selected_value = copyList[FirstPriceItemIndex][`option${i + 1}_value`];
                selected_value_label = copyList[FirstPriceItemIndex][`option${i + 1}_value_title`];
            }
            //如果有sku选中
            if (checkedSkuInfo) {
                selected_value = checkedSkuInfo[`option${i + 1}_value`];
                selected_value_label = checkedSkuInfo[`option${i + 1}_value_title`];
            }

            this.attrOption.push({
                name: "",
                isImg: false,
                selected_value_label: selected_value_label,
                selected_value: selected_value,
                value: []
            });
        }
        this.setSkuOption();
    } else {
        this.setSelectedVal(copyList[0]);
        this.setPriceVal(copyList[0]);
    }
};

//设置显示按钮
omesaasProduct.prototype.setButtonGroup = function (item) {
    if (item.available) {
        this.formDom.find(".product-cart-group").show();
        this.formDom.find(".product-payment-box").show();
        this.formDom.find(".product-out-of-stock").hide();
    } else {
        this.formDom.find(".product-cart-group").hide();
        this.formDom.find(".product-payment-box").hide();
        this.formDom.find(".product-out-of-stock").show();
    }
};

//获取当前sku属性
omesaasProduct.prototype.checkedSKu = function (item) {
    const barcode = moi.getUrlParam("variant_barcode");
    const sku = moi.getUrlParam("variant_sku");
    const sku_code = moi.getUrlParam("variant_sku_code");

    if (barcode === "" && sku === "" && sku_code === "") {
        return false;
    }

    if (sku_code) {
        return this.variant.find(function (el) {
            return el.sku_code === sku_code;
        });
    }

    if (sku) {
        return this.variant.find(function (el) {
            return el.sku === sku;
        });
    }

    if (barcode) {
        return this.variant.find(function (el) {
            return el.barcode === barcode;
        });
    }
};

omesaasProduct.prototype.isCurrentOptionBuy = function (item) {
    // const quantity = item.quantity || item.inventory_quantity || 0;
    // if ((this.product.inventory_policy === 1 || this.product.inventory_policy === 3) && quantity === 0 && this.product.inventory_tracking === 1) {
    //     console.warn(this.product.inventory_policy);
    //     return false;
    // }
    return item.available ? true : false;
};

omesaasProduct.prototype.optionIndexKey = function (index) {
    return { title: `option${index + 1}_title`, value: `option${index + 1}_value_title`, id: `option${index + 1}_value` };
};

//获取可选项
omesaasProduct.prototype.getOptional = function (sku) {
    for (let i = 0; i < sku.length; i++) {
        const element = sku[i];
        if (this.isCurrentOptionBuy(element)) {
            return element;
        }
    }
    return false;
};

omesaasProduct.prototype.setSkuOption = function () {
    let filterSKu = JSON.parse(JSON.stringify(this.variant));
    const product_sku_options = themeConfig.global.product_sku_options;
    let isSetOptionImg = false;

    this.attrOption.map((attr, i) => {
        const { title, value, id } = this.optionIndexKey(i);

        //设置当前选项卡是否需要显示图片
        for (let index = 0; index < filterSKu.length; index++) {
            const element = filterSKu[index];
            if (!attr.name) {
                attr.name = element[title];
                if (product_sku_options && product_sku_options.indexOf(attr.name) > -1 && !isSetOptionImg) {
                    attr.isImg = true;
                    isSetOptionImg = true;
                }
            }

            const currentIndex = attr.value.findIndex((val) => val.name === element[value]);
            if (currentIndex > -1) {
                attr.value[currentIndex].quantity += element.inventory_quantity;

                if (!attr.value[currentIndex].available && element.available) {
                    attr.value[currentIndex].available = element.available;
                }
            } else {
                attr.value.push({
                    name: element[value],
                    value: element[id],
                    available: element.available,
                    image: element.image || "",
                    quantity: element.inventory_quantity
                });
            }
        }

        //如果选择过滤选择的数据
        if (attr.selected_value) {
            const currentOption = attr.value.filter((el) => el.value === attr.selected_value);

            //如果没有匹配项；循环获取满足条件的第一条
            if (!currentOption.length) {
                const option = this.getOptional(filterSKu);
                attr.selected_value = option[id];
                attr.selected_value_label = option[value];
            }

            filterSKu = filterSKu.filter((el) => el[id] === attr.selected_value);

            //如果没有信息清空信息
            if (!filterSKu.length) {
                attr.selected_value = "";
                attr.selected_value_label = "";
                this.setSelectedVal(false);
            }

            if (i === this.attrOption.length - 1 && filterSKu.length === 1 && attr.selected_value) {
                this.setSelectedVal(filterSKu[0]);
                this.setPriceVal(filterSKu[0]);
            }
        }

        return attr;
    });
    this.render();
};

//设置价格
omesaasProduct.prototype.setPriceVal = function (currentSku) {
    if (this.renderOption) {
        this.numberNode.html(formatMoney(currentSku.price, oemcart_currency));

        if (parseFloat(currentSku.compare_at_price) > parseFloat(currentSku.price)) {
            this.marketNode.html(formatMoney(currentSku.compare_at_price, oemcart_currency));
        } else {
            this.marketNode.html("");
        }
        this.setButtonGroup(currentSku);
    }
};

//设置选中的val
omesaasProduct.prototype.setSelectedVal = function (currentSku) {
    const product = this.product;
    const params = this.params;
    if (!currentSku) {
        this.params = {
            src: product.src,
            productTitle: product.title,
            product_id: product.id,
            sku_value: "",
            quantity: params.quantity || 1
        };
    } else {
        this.params = Object.assign(params, currentSku);

        //设置选中的sku
        if (this.optionLength && this.params.sku) {
            let skuName = [];
            for (let i = 0; i < this.optionLength; i++) {
                const title = this.params[`option${i + 1}_title`];
                const value = this.params[`option${i + 1}_value_title`];
                skuName.push(`${title}:${value}`);
            }
            this.params["sku_value"] = skuName.join("<br/>");
        }
    }

    //设置url 链接
        if (location.pathname.indexOf("/products") !== -1 && this.params.sku_code && this.isMainProduct) {
            history.replaceState(null, null, moi.setUrlParams(location.href, { variant_sku_code: this.params.sku_code }));
        }
        
        // 更新库存显示
        if (this.inventoryNode && this.inventoryNode.length > 0) {
            this.updateInventoryDisplay(currentSku);
        }

    //如果是主商品存入主商品选中数据
    if (this.isMainProduct) {
        $(".mo-editor-reset")
            .find("img")
            .each(function (index, element) {
                $(this).attr("referrer", "no-referrer");
            });
        moi.setPageStorage("mian_product_params", this.params);
    }
    moi.onEvent("productOptionChange", this.params);
    //设置当前积木块相关的选中商品数据
    moi.setPageStorage("product_params" + this.block_id, this.params);
    this.changeOption && this.changeOption.call(this, this.params);
};

omesaasProduct.prototype.optionCompare = function (html) {
    const skuNode = $(`<div>${html}</div>`);
    if (this.oldAttrOption.length) {
        this.attrOption.forEach((item, index) => {
            if (item.selected_value !== this.oldAttrOption[index].selected_value) {
                const valIndex = item.value.findIndex((val) => val.value === item.selected_value);
                if (index > -1) {
                    const currentNode = this.skuNode.find(".moi-product-sku-value").eq(index).find(".product-sku-values-item").eq(valIndex);
                    const labelNode = this.skuNode.find(".moi-product-sku-label").eq(index);
                    currentNode.addClass("product-sku-values-item-active").siblings().removeClass("product-sku-values-item-active");
                    labelNode.html(skuNode.find(".moi-product-sku-label").eq(index).html());
                }
            }

            if (item.value.map((el) => el.value).toString() !== this.oldAttrOption[index].value.map((el) => el.value).toString()) {
                this.skuNode.find(".moi-product-sku-value").eq(index).html(skuNode.find(".moi-product-sku-value").eq(index).html());
            }
        });
    } else {
        this.skuNode.html(html);
    }

    this.oldAttrOption = JSON.parse(JSON.stringify(this.attrOption));
};

// 渲染页面
omesaasProduct.prototype.render = function () {
    if (this.renderOption) {
        // this.oldAttrOption = this.attrOption;

        const self = this;
        engine
            .parseAndRender(this.skuTemplate, {
                skus: this.attrOption,
                productSkuStyle: themeConfig.global.product_sku_style || "image_text"
            })
            .then(function (liquidHtml) {
                self.optionCompare(liquidHtml);
                window.addLazyImages && addLazyImages(self.skuNode.find("img[data-src]"));
            });
    }
    if (!this.product.available) {
        this.setSelectedVal({ quantity: this.params.quantity });
    }
};

//验证数据
omesaasProduct.prototype.verifyOption = function (type) {
    //库存为0时不能购买
    if (this.product.available === 0) {
        moi.alertInfo({ content: "quantity empty" });
        return false;
    }

    if (type === "cart" && !this.cartShake) {
        return false;
    }

    if (type === "buy" && !this.buyShake) {
        return false;
    }
    for (let i = 0; i < this.attrOption.length; i++) {
        if (!this.attrOption[i].selected_value) {
            moi.tooltip({
                el: this.skuNode.find(".product-sku-name").eq(i),
                content: "select " + this.product.options[i].name
            });
            return false;
        }
    }
    return true;
};

//获取ec_data参数
omesaasProduct.prototype.getEcData = function () {
    const self = this;
    return {
        ec_data_id: self.product.id,
        ec_data_from: self.data_from,
        ec_data_name: encodeURIComponent(self.product.title),
        ec_data_price: self.params.price,
        ec_data_discount_price: self.params.price,
        ec_data_spu: self.product.spu,
        ec_data_image: self.product.src,
        ec_data_category: self.product.product_type,
        ec_data_uniq_id: self.product.id,
        ec_data_sku: self.params.sku,
        ec_data_sku_code: self.params.sku_code,
        ec_data_quantity: self.params.quantity,
        ec_data_sku_name: self.params.sku_value || "",
        ec_currency_code: self.ec_currency_code,
        ec_data_action_type: ""
    };
};

omesaasProduct.prototype.share = function (platform) {
    const self = this;
    const ec_data = {
        ec_data_id: self.product.id,
        ec_data_from: self.data_from,
        ec_data_name: encodeURIComponent(self.product.title),
        ec_data_price: self.product.variant.price,
        ec_data_discount_price: self.product.variant.price,
        ec_data_spu: self.product.spu,
        ec_data_image: self.product.src,
        ec_data_category: self.product.product_type,
        ec_data_uniq_id: self.product.id,
        ec_data_sku: self.product.variant.sku,
        ec_data_sku_code: self.product.variant.sku_code,
        ec_data_quantity: 1,
        ec_data_sku_name: self.product.variant.sku_value,
        ec_currency_code: self.ec_currency_code,
        ec_data_action_type: ""
    };
    ec_data.ec_data_action_type = "share_product";
    callback_share_product(ec_data, platform);
};

//回调添加购物车
omesaasProduct.prototype.callbackAddToCart = function () {
    const self = this;
    const ec_data = self.getEcData();
    ec_data.ec_data_action_type = "add_to_cart";
    callback_add_to_cart(ec_data);
};

//加入购物车
omesaasProduct.prototype.addCart = function (complete, success) {
    const self = this;
    self.cartShake = false;
    let ret = moi.onEvent("payVerified", { property: [], product: this.params, code: 200 });

    if (ret.params.code === 200) {
        self.params["property"] = ret.params.property;
        moi.ajax({
            url: "/cart/add",
            type: "post",
            data: JSON.stringify({
                product_id: this.product.id,
                sku_code: this.params.sku_code,
                quantity: this.params.quantity,
                data_from: self.data_from,
                property: ret.params.property
            }),
            complete() {
                self.cartShake = true;
            },
            success: function (data) {
                complete && complete.call(this);
                if (!data.code) {
                    if (window.callback_add_to_cart) {
                        self.callbackAddToCart();
                    }
                    var num = parseInt(moi.getPageStorage("cart_number") || 0) + self.params.quantity;
                    moi.changeCartNumber(num);
                    miniCart();
                    self.setSelectedVal({ subtotalPrice: data.data.items_subtotal_price });
                }
                success && success.call(self, data);
            }
        });
    } else {
        self.cartShake = true;
        complete && complete.call(this);
    }
};

//立即购买
omesaasProduct.prototype.buynow = function (complete, success) {
    const self = this;
    self.buyShake = false;
    let ret = moi.onEvent("payVerified", { property: [], product: this.params, code: 200 });
    if (ret.params.code === 200) {
        self.params["property"] = ret.params.property;
        moi.ajax({
            url: "/cart/buynow",
            type: "post",
            data: JSON.stringify({
                product_id: this.product.id,
                sku_code: this.params.sku_code,
                quantity: this.params.quantity,
                data_from: self.data_from,
                property: ret.params.property
            }),
            complete() {
                self.buyShake = true;
            },
            success: function (ret) {
                if (!ret.code && window.callback_add_to_cart) {
                    self.callbackAddToCart();
                }
                complete && complete.call(this);
                success && success.call(self, ret);
            }
        });
    } else {
        self.buyShake = true;
        complete && complete.call(this);
    }
};

//购物车弹窗
omesaasProduct.prototype.cartLayer = function () {
    const option = JSON.parse(JSON.stringify(this.params));
    let isProperty = false; //是否支持自定义
    if (option.property.length) {
        isProperty = option.property.some((el) => typeof el.params !== "string");
    }
    const subtotalPrice = formatMoney(parseFloat(option.subtotalPrice || 0), oemcart_currency);
    const popupLayer = moi.popup();
    engine
        .parseAndRender($("#omesaas-popup-addPurchase-success").html(), {
            option: option,
            subtotalPrice: subtotalPrice,
            isProperty: isProperty,
            lang: window.lang
        })
        .then(function (html) {
            popupLayer.addContent(html);
            const temp = popupLayer.temp;
            //提交购物车跳转地址填写
            const submitNodes = temp.find(".cart-button");

            submitNodes.on("click", function () {
                temp.find(".cart_form").submit();
                popupLayer.close();
            });
        });
};

// 更新库存显示方法
omesaasProduct.prototype.updateInventoryDisplay = function(currentSku) {
    if (!this.inventoryNode || !this.inventoryNode.length || !currentSku) {
        return;
    }
    
    const inventoryQuantity = currentSku.inventory_quantity || 0;
    let statusClass = '';
    let statusText = '';
    
    if (inventoryQuantity <= 0) {
        // 缺货状态
        statusClass = 'status-red';
        statusText = 'Out of stock';
    } else if (inventoryQuantity <= 10) {
        // 低库存状态
        statusClass = 'status-orange';
        statusText = `Only ${inventoryQuantity} item(s) left`;
    } else {
        // 有货状态
        statusClass = 'status-green';
        statusText = `Inventory: ${inventoryQuantity} remaining`;
    }
    
    // 更新库存显示
    this.inventoryNode.html(`
        <div class="status-dot ${statusClass}"></div>
        <span class="inventory-text ${statusClass}">${statusText}</span>
    `);
};

export default omesaasProduct;

// 背景图
$("body").prepend(`<img src="背景图地址" style="width: 100%;height: auto;" />`)

// 背景图加logo
$("body").prepend(`
<style>
@media screen and (max-width: 1000px) {
#logo_banner{
    padding:0 !important;
}
}
</style>
<div style="position: relative;background-image: url(https://cdn.shopify.com/s/files/1/0293/9277/files/black-background_2000x.png?v=1697221145);
background-color: rgb(51, 51, 51);
background-position: 50% 50%;
background-size: cover;">
<div id="logo_banner" style="width: 90%;align-items: center; padding: 20px 5%;box-sizing: border-box;max-width: 1244px;margin: 0 auto;">
<a href="/"><img src="${storeConfig.logo}" style="width: 50px;height: auto;" /></a>
</div>
</div>`)


// logo 加购物车
$("body").prepend(`
<style>
@media screen and (max-width: 1000px) {
#logo_banner{
    padding:0 !important;
}
}
</style>
<div style="position: relative;">
<div style="height:100px;background-color: #000;"></div>
<div id="logo_banner" style="position: absolute;top: 50%;width: 90%;    align-items: center;padding: 0 5%;box-sizing: border-box;max-width: 1244px;left: 50%;transform: translate(-50%,-50%);display: flex;justify-content: space-between;">
<a href="/">
<img src="${storeConfig.logo}" style="width: 50px;height: auto;" />
</a>
<a href="/cart" style="color:#fff">
<svg width="28" height="28" viewBox="0 0 28 28" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M6.10959 22L6 9H22L21.8904 22H6.10959Z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path>
<path d="M10 9V8C10 5.79086 11.7909 4 14 4V4C16.2091 4 18 5.79086 18 8V9" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path>
</svg>
</a>
</div>
</div>`)
